package com.jdd.pedicure.controller;

import com.jdd.pedicure.Utils.MD5Utils;
import com.jdd.pedicure.entity.Admin;
import com.jdd.pedicure.entity.Result;
import com.jdd.pedicure.service.AdminService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;


@RequestMapping("admin")
@Controller
public class AdminController {
    @Resource
    AdminService adminService;

    @RequestMapping("goAdmin")
    public String goAdmin() {
        return "admin";
    }

    @RequestMapping("goAdd")
    public String goAdd(Integer id, HttpServletRequest request) {
        Admin admin = new Admin();
        if (id != null) {
            admin = adminService.queryById(id);
        }
        request.setAttribute("admin", admin);
        return "adminAdd";
    }

    @RequestMapping("delete")
    @ResponseBody
    public Result delete(int id) {
        Result result = new Result();
        adminService.delete(id);
        result.setCode("0");
        result.setMsg("删除成功");
        return result;
    }

    @RequestMapping("save")
    @ResponseBody
    public Result save(@RequestBody Admin admin) {
        Result result = new Result();
        try {
            String pwd = MD5Utils.EncoderByMd5(admin.getPassword());
            admin.setPassword(pwd);
            adminService.saveOrUpdate(admin);
            result.setCode("0");
            result.setMsg("更新用户成功！");
        } catch (Exception e) {
            result.setCode("1");
            result.setMsg("更新用户失败！请重试");
        }
        return result;

    }

    @ResponseBody
    @RequestMapping("getData")
    public Result<Admin> getData(Result<Admin> result, Admin example) {
        result.setExample(example);
        adminService.queryByPage(result);
        String password = result.getData().get(0).getPassword();
        System.out.println(password);
        result.setCode("0");
        return result;
    }

    @ResponseBody
    @RequestMapping("/deletes")
    public Result<Admin> doDelAdmins(@RequestBody List<Admin> admins) {
        adminService.deletes(admins);
        Result<Admin> itemResult = new Result<>();
        itemResult.setCode("0");
        return itemResult;
    }
}
